package com.ithema.edu.info.manager;

import com.ithema.edu.info.manager.service.TeacherService;
import org.dom4j.Document;

import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanFactory {
    private static Map<String, String> map = new HashMap<>();

    static {
        try {
            SAXReader saxReader = new SAXReader();//用dom4j解析xml文件
            InputStream in = TeacherService.class.getClassLoader().getResourceAsStream("applicationContext.xml");
            Document read =saxReader.read(in);
            Element rootElement = read.getRootElement();
            List<Element> beans = rootElement.elements("bean");
            for (
                    Element bean : beans) {
                String id = bean.attributeValue("id");
                String className = bean.attributeValue("class");

                map.put(id, className);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    public static Object getBean(String id){
        String className = map.get(id);
        try {
            return Class.forName(className).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


}
